// 已选城市tab
<template>
  <div class="current-city-bay">
    <div class="current-city">
      <div
        class="current-city-item"
        v-for="(city, index) in currentCity"
        :key="city.id"
        :class="{ active: cityHeadTabsIndex === index }"
        @click="onCLickcityHeadTabs(index)"
      >
        {{ city.name }}
      </div>
    </div>
    <div
      class="current-slider"
      :style="{ left: sliderLeft, width: sliderWidth }"
    ></div>
  </div>
</template>

<script>
export default {
  name: "cityTabs",
  props: {
    currentCity: {
      type: Array,
      default: () => [],
    },
    cityHeadTabsIndex: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      sliderLeft: 0, // 选择地区滑块的left
      sliderWidth: "30px", // 滑块的width
    };
  },
  watch: {
    cityHeadTabsIndex: {
      handler(index) {
        const { width, left } = this.getSliderLeftWidth(index);
        this.sliderWidth = width + "px";
        this.sliderLeft = left + "px";
      },
    },
  },
  methods: {
    onCLickcityHeadTabs(index) {
      this.$emit("checkIndex", index);
    },
    getSliderLeftWidth(index) {
      const targetEl = [
        ...document.querySelectorAll(".current-city-item"),
      ].find((currentValue, i) => {
        return i === index;
      });
      return {
        width: targetEl.offsetWidth,
        left: targetEl.offsetLeft,
      };
    },
  },
};
</script>

<style lang="scss" scoped>
.current-city-bay {
  position: relative;
  padding-bottom: 5px;
  margin: 0 16px;
  .current-city {
    display: flex;
    flex-wrap: wrap;
    .current-city-item {
      max-width: 90px;
      margin-right: 20px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      position: relative;
      color: #999;
      font-weight: 500;
      transition: all 0.5s;
      &.active {
        color: #222;
      }
    }
  }
  .current-slider {
    transition: all 0.4s;
    position: absolute;
    bottom: 0px;
    left: 0;
    height: 1px;
    background-color: #222;
  }
}
</style>